package com.example.My.service.Impl;

import com.example.My.auProvider.EmailCodeAuthenticationProvider;
import com.example.My.auToken.EmailCodeAuthenticationToken;
import com.example.My.common.ResponseResult;
import com.example.My.pojo.LoginUser;
import com.example.My.pojo.Mail;
import com.example.My.pojo.User;
import com.example.My.service.LoginService;
import com.example.My.service.MailService;
import com.example.My.service.UserService;
import com.example.My.tools.JwtTool;
import com.example.My.tools.RandomTool;
import com.example.My.tools.RedisCache;
import io.netty.util.internal.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * Author: 谢宇
 * CreatTime 2023/11/5 14:57
 * Version 1.0.0
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Resource
    private UserService userService;

    @Resource
    private RedisCache redisCache;

    @Resource
    private MailService mailService;

    /**
     * 验证码
     * @param CodeName
     * @return
     */
    @Override
    public ResponseResult sendCode(Authentication CodeName) {
        Authentication authenticate = new EmailCodeAuthenticationProvider(userService).authenticate(CodeName);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("邮箱错误");
        }
        LoginUser principal = (LoginUser) authenticate.getPrincipal();
        User user = principal.getUser();
        RandomTool randomTool=new RandomTool(6);
        String code = randomTool.randomNum();
        mailService.sendHtmlMail(new Mail(user.getEmail(),user.getNickName(),"登录验证码","1",code,null));
        int i = user.getEmail().indexOf("@");
        // todo 使用qq号后四位作key值的id,设置5分钟的过期时间
        redisCache.setCacheObject("Code:"+user.getId()+":"+user.getEmail().substring(i-4,i),code,5, TimeUnit.MINUTES);
        return new ResponseResult(200,"发送成功");
    }

    /**
     * todo 用于账号密码登录，此方法被应用于反射（loginContext）
     * @param user
     * @return
     */
    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        //调用了authenticationManager接口内的authenticate的ProviderManager实现，内部调用了自己定义的userDetailsServiceImpl方法的实现
        Authentication authenticate =authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtTool.createJWT(userId);
        //authenticate存入redis 后面调用接口需要使用的是authenticate令牌
        redisCache.setCacheObject("login:"+userId,loginUser);
        //把token响应给前端
        System.out.println(jwt);
        HashMap<String,String> map = new HashMap<>();
        map.put("token",jwt);
        return new ResponseResult(200,"登陆成功",map);
    }

    /**
     * todo 用于邮箱登录，此方法被应用于反射（loginContext）
     * @param user
     * @return
     */
    @Override
    public ResponseResult loginByEmail(User user) {
        //获取验证 springSecurity权限
        Authentication emailAuthentication=new EmailCodeAuthenticationToken(user.getEmail());
        //通过去查找数据库获取springSecurity令牌
        Authentication authenticate = new EmailCodeAuthenticationProvider(userService).authenticate(emailAuthentication);
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("邮箱未注册");
        }
        int i = user.getEmail().indexOf("@");
        Object Code = redisCache.getCacheObject("Code:" + userId + ":" + user.getEmail().substring(i - 4, i));
        if(Code==null||Objects.isNull(Code)){
            return new ResponseResult<>(400,"该验证码已经过期了！！！",null);
        }
        String emailCode = Code.toString();
        if(emailCode.equals(user.getCode())||emailCode== user.getCode()){
            //生成jwt传给前端
            String jwt = JwtTool.createJWT(userId);
            HashMap<String,String> map=new HashMap<>();
            map.put("token",jwt);
            //生成令牌存入redis
            redisCache.setCacheObject("login:"+userId,loginUser);
            return new ResponseResult(200,"登录成功",map);
        }else {
            return new ResponseResult(400,"验证码错误",null);
        }
    }

    /**
     * todo 用于手机登录，此方法被应用于反射（loginContext）
     * @param user
     * @return
     */
    @Override
    public ResponseResult loginByPhone(User user) {
        return null;
    }



    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();
        redisCache.deleteObject("login:"+userid);
        return new ResponseResult(200,"退出成功");
    }



}
